package com.soecode.lyf.web;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.soecode.lyf.config.ImageUtils;
import com.soecode.lyf.dto.Result;
import com.soecode.lyf.entity.Comment;
import com.soecode.lyf.service.CommetService;

@Controller
//@Scope("session") // 表示会话级别
@RequestMapping("/comment") // url:/模块/资源/{id}/细分 /seckill/list
public class CommetController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private CommetService commentservice;
	private List<Comment> List;
	
	//required = true（要求必须携带参数）,defaultValue = "1" （带了参数会接收，如果没带参数则设置一个默认值为1）
	@ResponseBody
	@RequestMapping(value="/commentlist", method = RequestMethod.GET) // 查询所有问题
    public Result findAll(@RequestParam(name="page",required = true,defaultValue = "1")int page,@RequestParam(name="size",required=true,defaultValue = "4") int size, Model model, int sortType) throws Exception{
    	Result result = new Result();
    	if(!StringUtils.isEmpty(page)&&!StringUtils.isEmpty(size)&&sortType == 0) { // 按热度排序
    		System.out.println("1");
    	PageHelper.startPage(page,size);
    	List=commentservice.selectAll(sortType);
    	}else if(!StringUtils.isEmpty(page)&&!StringUtils.isEmpty(size)&&sortType == 1){ // 按时间排序
    		System.out.println("2");
    		PageHelper.startPage(page,size);
        List=commentservice.selectAll(sortType);
    	}
    	PageInfo<Comment> page1 = new PageInfo<Comment>(List);
    	/*System.out.println("总数量：" + page1.getTotal());
    	System.out.println("当前页查询记录：" + page1.getList().size());
    	System.out.println("当前页码：" + page1.getPageNum());
    	System.out.println("每页显示数量：" + page1.getPageSize());
    	System.out.println("总页：" + page1.getPages());*/
        model.addAttribute("PAGEINFO",List);
        model.addAttribute("PAGESUM",page1.getTotal());
        result = new Result(0,model,"查询分页成功");
        return result;
    }
	
	@ResponseBody
	@RequestMapping(value="/mycommentlist", method = RequestMethod.GET) // 查询所有问题
    public Result findMyAll(@RequestParam(name="page",required = true,defaultValue = "1")int page,@RequestParam(name="size",required=true,defaultValue = "4") int size, Model model, int sortType, String userid) throws Exception{
    	Result result = new Result();
    	if(!StringUtils.isEmpty(page)&&!StringUtils.isEmpty(size)&&!StringUtils.isEmpty(userid)&&sortType == 0) {
    	  PageHelper.startPage(page,size);
          List<Comment> list=commentservice.selectMyAll(userid);
      	  PageInfo<Comment> page1 = new PageInfo<Comment>(list);
      	/*System.out.println("总数量：" + page1.getTotal());
      	System.out.println("当前页查询记录：" + page1.getList().size());
      	System.out.println("当前页码：" + page1.getPageNum());
      	System.out.println("每页显示数量：" + page1.getPageSize());
      	System.out.println("总页：" + page1.getPages());*/
          model.addAttribute("PAGEINFO",list);
          model.addAttribute("PAGESUM",page1.getTotal());
          result = new Result(0,model,"查询分页成功");
    	}
        return result;
    }
	
	@ResponseBody
	@RequestMapping(value="/questionPrase", method = RequestMethod.GET) // 查询所有问题
	public Result questionPrase(String userid, Model model) {
	Result result = new Result();
	if(!StringUtils.isEmpty(userid)) {
		List<Comment> List = commentservice.getQuestionPrase(userid);
		model.addAttribute("QUESTIONPRASE",List);
		result = new Result(0,model,"查询成功");
	}
	return result;
	}
	
	@ResponseBody
	@RequestMapping(value="/postdetail", method = RequestMethod.GET) // 根据id查询问题
	public Result getPostDetail(int page,int size,String questionid, Model model,String userid,String sort) {
		Result result = new Result();
		if(!StringUtils.isEmpty(questionid)&&!StringUtils.isEmpty(userid)&&!StringUtils.isEmpty(page)&&!StringUtils.isEmpty(size)&&StringUtils.isEmpty(sort)) {
		List List = commentservice.getPostDetail(questionid,userid);
		Map<String,Object> map = (Map<String, Object>) List.get(0);
		String adopt = map.get("adopt").toString();
		if(StringUtils.isEmpty(adopt)) {
			adopt = "";
		}
		PageHelper.startPage(page,size);
		List<Comment> commentList = commentservice.getCommentList(questionid,adopt);
    	PageInfo<Comment> page1 = new PageInfo<Comment>(commentList);
    	List<Comment> questionPraseList = commentservice.getQuestionPrase(userid); // 问题点赞集合
    	List<Comment> commentPraseList = commentservice.getCommentPrase(userid); // 问题点赞集合
    	List<Comment> replyPraseList = commentservice.getReplyPrase(userid); // 回复点赞集合
		List<Comment> questionReplyList = commentservice.getReplyList(questionid,userid); // 问题回复集合
    	System.out.println("总数量：" + page1.getTotal());
    	System.out.println("当前页查询记录：" + page1.getList().size());
    	System.out.println("当前页码：" + page1.getPageNum());
    	System.out.println("每页显示数量：" + page1.getPageSize());
    	System.out.println("总页：" + page1.getPages());
		model.addAttribute("COMMENTLIST",commentList);
		model.addAttribute("POSTINFO",List);
		model.addAttribute("ReplyLIST",questionReplyList);
		model.addAttribute("QUESTIONPRASE",questionPraseList);
		model.addAttribute("COMMENTPRASE",commentPraseList);
		model.addAttribute("REPLYPRASE",replyPraseList);
		result = new Result(0,model,"查询成功");
		}else if(!StringUtils.isEmpty(questionid)&&!StringUtils.isEmpty(userid)&&!StringUtils.isEmpty(page)&&!StringUtils.isEmpty(size)&&!StringUtils.isEmpty(sort)) {
			List List = commentservice.getPostDetail(questionid,userid);
			Map<String,Object> map = (Map<String, Object>) List.get(0);
			String adopt = map.get("adopt").toString();
			if(StringUtils.isEmpty(adopt)) {
				adopt = "";
			}
			PageHelper.startPage(page,size);
			List<Comment> commentList = commentservice.getCommentList(questionid,adopt);
	    	PageInfo<Comment> page1 = new PageInfo<Comment>(commentList);	
	    	model.addAttribute("COMMENTLIST",commentList);
	    	result = new Result(0,model,"查询成功");
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value="/postcomment", method = RequestMethod.GET) // 提交评论
	public Result getCommentList(int questionid, Model model, String userid,String content,String time) {
		Result result = new Result();
		if(!StringUtils.isEmpty(questionid)&&!StringUtils.isEmpty(userid)&&!StringUtils.isEmpty(content)&&!StringUtils.isEmpty(time)) {
			Comment cmnt = new Comment();
			cmnt.setQuestion_id(questionid);
			cmnt.setUserid(userid);
			cmnt.setContent_p(content);
			cmnt.setCreatetime_p(time);
			System.out.println("插入之前"+cmnt);
			int i = commentservice.toComment(cmnt); // 插入评论
			if(i!=0) {
				int commentId = cmnt.getComment_id(); // 评论插入之后的id
				int j = commentservice.addCommentNum(questionid); // 增加问题评论数目
				Map map = commentservice.selectComment(commentId); // 根据评论id查询评论
				if(j!=0 && map!=null) {
					model.addAttribute("COMMENT",map);
					result = new Result(0,model,"评论成功");
				}
			}
			}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value="/postreply", method = RequestMethod.GET) // 回复
	public Result getReplyList(int commentid, Model model, String userid, String content, String time) {
		Result result = new Result();
		if(!StringUtils.isEmpty(commentid)&&!StringUtils.isEmpty(userid)&&!StringUtils.isEmpty(content)&&!StringUtils.isEmpty(time)) {
			String replyuserid = commentservice.selectReplyUserid(commentid);
			System.out.println("被回复人id"+replyuserid);
			Comment cmnt = new Comment();
			cmnt.setComment_id(commentid);
			cmnt.setUserid(userid);
			cmnt.setContent_r(content);
			cmnt.setCreatetime_r(time);
			cmnt.setReplyuserid(replyuserid);
			int reply = commentservice.toReply(cmnt); 
			if(reply!=0) { // 回复插入成功
				int id = cmnt.getId(); // 获取插入回复的id
				int commentnum = commentservice.addReplyNum(commentid);
				if(commentnum!=0) { // 回复数+1
				HashMap map = commentservice.getReplyInfo(id);
				model.addAttribute("ReplyInfo",map);
				result = new Result(0,model,"回复成功");	
				}
			}
			}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value="/postenjoy", method = RequestMethod.GET) // 问题点赞
	public Result postEnjoy(String userid,int questionid,int enjoyType) {
		Result result = new Result();
		if(!StringUtils.isEmpty(userid)&&!StringUtils.isEmpty(questionid)&&enjoyType == 0) { // 点赞
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			int postenjoy = commentservice.postEnjoy(uuid,userid,questionid);
			if(postenjoy!=0) {
			int addenjoynum = commentservice.addEnjoyNum(questionid);
			 if(addenjoynum!=0) {
				 result = new Result(0,"点赞成功");
			 }
			}
		}else if(!StringUtils.isEmpty(userid)&&!StringUtils.isEmpty(questionid)&&enjoyType == 1){
			int postenjoy = commentservice.postEnjoyQuit(userid,questionid);
			if(postenjoy!=0) {
			int addenjoynum = commentservice.reduceEnjoyNum(questionid);
			 if(addenjoynum!=0) {
				 result = new Result(0,"取消点赞");
			 }
			}
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value="/commentenjoy", method = RequestMethod.GET) // 评论点赞
	public Result commentEnjoy(String userid,int commentid,int enjoyType) {
		Result result = new Result();
		if(!StringUtils.isEmpty(userid)&&!StringUtils.isEmpty(commentid)&&enjoyType == 0) { // 点赞
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			int postenjoy = commentservice.commentEnjoy(uuid,userid,commentid);
			if(postenjoy!=0) {
			int addenjoynum = commentservice.addCommentEnjoyNum(commentid,userid);
			 if(addenjoynum!=0) {
				 result = new Result(0,"点赞成功");
			 }
			}
		}else if(!StringUtils.isEmpty(userid)&&!StringUtils.isEmpty(commentid)&&enjoyType == 1){
			int postenjoy = commentservice.CommentEnjoyQuit(userid,commentid);
			if(postenjoy!=0) {
			int addenjoynum = commentservice.reduceCommentEnjoyNum(commentid,userid);
			 if(addenjoynum!=0) {
				 result = new Result(0,"取消点赞");
			 }
			}
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value="/replyenjoy", method = RequestMethod.GET) // 评论点赞
	public Result replyEnjoy(String userid,int replyid,int enjoyType) {
		Result result = new Result();
		if(!StringUtils.isEmpty(userid)&&!StringUtils.isEmpty(replyid)&&enjoyType == 0) { // 点赞
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			int postenjoy = commentservice.replyEnjoy(uuid,userid,replyid);
			if(postenjoy!=0) {
			int addenjoynum = commentservice.addReplyEnjoyNum(replyid,userid);
			 if(addenjoynum!=0) {
				 result = new Result(0,"点赞成功");
			 }
			}
		}else if(!StringUtils.isEmpty(userid)&&!StringUtils.isEmpty(replyid)&&enjoyType == 1){
			int postenjoy = commentservice.ReplyEnjoyQuit(userid,replyid);
			if(postenjoy!=0) {
			int addenjoynum = commentservice.reduceReplyEnjoyNum(replyid,userid);
			 if(addenjoynum!=0) {
				 result = new Result(0,"取消点赞");
			 }
			}
		}
		return result;
	}
	@ResponseBody
	@RequestMapping(value="/topost", method = RequestMethod.POST) // 评论点赞
	public Result toPost(String userid, HttpServletRequest request, @RequestParam("file") MultipartFile[] pictureFile, Model model, String title, String textarea, String label) {
		Result result = new Result();
		if(!StringUtils.isEmpty(userid)) {
		Comment cmnt = new Comment();
				String imgPath = null;
				//UserInfo userinfo = new UserInfo();
				try {
		            //ImageUtils为之前添加的工具类
					imgPath = ImageUtils.upload(request, pictureFile);
					Date time1 = new Date();
			        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			        String thistime = df.format(time1);
					cmnt.setImg_arr(imgPath);
					cmnt.setTitle(title);
					cmnt.setContent(textarea);
					cmnt.setLabel(label);
					cmnt.setUserid(userid);
					cmnt.setTime(thistime);
					if (imgPath != null) {
						System.out.println("图片路径上传成功");
					}else{
						System.out.println("图片上传失败");
		            }
					// 将上传图片的地址封装到实体类
					//userinfo.setImg(imgPath);
					//将数据提交到数据库（包含文件和普通表单数据）
					int rowNo = commentservice.savePost(cmnt);
					if (rowNo != 0) { // 问题提交成功
						System.out.println("问题提交成功返回id"+rowNo);
						int reducejf = commentservice.reduceIntegral(userid);
						result = new Result(0,"提交成功");
						// 转发：forword，重定向：redirect
						//return "redirect:/user/findUsers.do";
					} else {
						result = new Result(1,"问题提交失败");
						//return "addUser";
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println("----------------图片上传失败！");
				}
			System.out.println("标题"+title);
			System.out.println("内容"+textarea);
			System.out.println("标签"+label);
			System.out.println("图片路径"+imgPath);
		}else {
			result = new Result(1,"登录过期");
		}
		return result;
	}
}
